import 'dart:convert';

import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_section_table_view/flutter_section_table_view.dart';
import 'package:ls_work/a_yyt/models/handover_new_area_entity.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/toast.dart';

import '../../util/flat_button.dart';

class HanoverAreaDetailPage extends StatefulWidget {
  // final HandoverNewAreaEntity detailInfo;
  final int? areaId;
  final String? reportDate;
  final int? dutyType;

  HanoverAreaDetailPage({
    Key? key,
    this.areaId,
    this.reportDate,
    this.dutyType,
  }); //this.detailInfo,
  @override
  _HanoverAreaDetailPageState createState() => _HanoverAreaDetailPageState();
}

class _HanoverAreaDetailPageState extends State<HanoverAreaDetailPage>
    with AutomaticKeepAliveClientMixin {
  HandoverNewAreaEntity _detailInfo = HandoverNewAreaEntity(elderInfos: []);
  TextEditingController textFieldEditer = TextEditingController();
  TextEditingController archiveTextFieldEditer = TextEditingController();
  bool _archive = false;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.areaId != null) {
        _fectData();
      }
    });
    eventBus.on(Constant.eventHandoverRefresh, (arg) {
      List target = arg;
      if (widget.areaId != null && target.first == widget.areaId) {
        _fectData();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: ScreenUtil.getScreenW(context),
          padding: EdgeInsets.all(15),
          margin: EdgeInsets.all(15),
          decoration: BoxDecoration(
            color: Colours.bg_color,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '${_detailInfo.reportDate ?? ''}  ${_detailInfo.dutyTypeDesc ?? ''}',
                style: TextStyles.textGray18,
              ),
              Gaps.vGap10,
              Text(
                '本区域入住${_detailInfo.elderCount ?? ''}位长者，交班涉及${_detailInfo.relateElderCount ?? ''}位长者，护工${_detailInfo.nurseCount}人',
                style: TextStyles.textGray18,
              ),
            ],
          ),
        ),
        Flexible(
          child: ((_detailInfo.elderInfos ?? []).length > 0)
              ? SectionTableView(
                  sectionCount: (_detailInfo.elderInfos ?? []).length,
                  numOfRowInSection: (section) =>
                      _detailInfo.elderInfos![section].infos?.length ?? 0,
                  divider: Gaps.line,
                  cellAtIndexPath: (section, row) {
                    return Container(
                      padding: EdgeInsets.all(15),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '${_detailInfo.elderInfos![section].infos![row].operator ?? ''}  ${_detailInfo.elderInfos![section].infos![row].reportDate ?? ''}',
                                style: TextStyles.textNormal18,
                              ),
                              _detailInfo.elderInfos![section]
                                          .customerElderName ==
                                      '交班总结'
                                  ? SizedBox()
                                  : SizedBox()
                              // GestureDetector(
                              //         behavior: HitTestBehavior.opaque,
                              //         onTap: () {
                              //           if (_detailInfo.areaAuth == false) {
                              //             Toast.show('权限限制');
                              //             return;
                              //           }
                              //           AppNavigator.push(
                              //             context,
                              //             HandoverRecordPage(
                              //               info: _detailInfo
                              //                   .elderInfos[section].infos[row],
                              //               customerElderName: _detailInfo
                              //                   .elderInfos[section]
                              //                   .customerElderName,
                              //               roomNo: _detailInfo
                              //                   .elderInfos[section].roomNo,
                              //               callBack: _fectData,
                              //             ),
                              //           );
                              //         },
                              //         child: Row(
                              //           children: [
                              //             Icon(
                              //               Icons.insert_comment,
                              //               color: Colours.text_gray,
                              //             ),
                              //             Gaps.hGap4,
                              //             Text(
                              //               _detailInfo.elderInfos[section]
                              //                           .infos[row].records !=
                              //                       null
                              //                   ? '${_detailInfo.elderInfos[section].infos[row].records.length ?? '0'}'
                              //                   : '0',
                              //               style: TextStyles.textGray16,
                              //             ),
                              //           ],
                              //         ),
                              //       ),
                            ],
                          ),
                          Gaps.vGap16,
                          Text(
                            "${_detailInfo.elderInfos![section].infos![row].content ?? ''}",
                            style: TextStyles.textGray16,
                          ),
                        ],
                      ),
                    );
                  },
                  headerInSection: (section) {
                    return Container(
                      padding: EdgeInsets.all(15),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: Divider.createBorderSide(
                            context,
                            color: Colours.line,
                            width: 1,
                          ),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '${_detailInfo.elderInfos![section].customerElderName ?? ''}  ${_detailInfo.elderInfos![section].roomNo ?? ''}',
                            style: TextStyles.textDark20,
                          ),
                          _detailInfo.elderInfos![section].customerElderName ==
                                  '交班总结'
                              ? SizedBox()
                              : GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    if (_detailInfo.areaAuth == false) {
                                      Toast.show('权限限制');
                                      return;
                                    }
                                    _bottomAddContentSheetAlert(
                                      _detailInfo.elderInfos![section],
                                      _detailInfo.id ?? 0,
                                    );
                                  },
                                  child: Text(
                                    '添加交接内容',
                                    style: TextStyle(color: Colors.blue),
                                  ),
                                ),
                        ],
                      ),
                    );
                  },
                )
              : Center(
                  child: Text(
                    '暂无数据',
                    style: TextStyles.textGray16,
                  ),
                ),
        ),
        GestureDetector(
          onTap: () {
            _bottomAddReportArchiveSheetAlert(_detailInfo.id ?? 0);
          },
          child: Container(
            width: ScreenUtil.getScreenW(context),
            height: 50,
            color: Colours.app_main,
            alignment: Alignment.center,
            child: Text('总结'),
          ),
        ),
      ],
    );
  }

  _fectData() {
    var map = {
      'reportDate': widget.reportDate,
      'dutyType': widget.dutyType,
      'areaId': widget.areaId,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.shiftingDutyArea}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            HandoverNewAreaEntity model =
                HandoverNewAreaEntity.fromJson(map['data']);
            if ((model.areas ?? []).length > 0) {
              setState(() {
                _detailInfo = model;
                if (model.summary != null) {
                  (_detailInfo.elderInfos ?? []).add(HandoverElderInfoEntity(
                      customerElderName: '交班总结',
                      roomNo: '',
                      infos: [
                        HandoverElderInfo(
                            operator: model.operator,
                            reportDate: model.summaryTime,
                            content: model.summary),
                      ]));
                }
              });
            } else {
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///添加交接内容
  _bottomAddContentSheetAlert(HandoverElderInfoEntity info, int? reportId) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: true,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom),
            child: Column(
              children: <Widget>[
                Gaps.vGap16,
                Text(
                  '添加交接内容：${info.customerElderName ?? ''}',
                  style: TextStyle(fontSize: 20, color: Colours.text_dark),
                ),
                Gaps.vGap15,
                Container(
                  padding: EdgeInsets.all(20),
                  color: Colors.white,
                  alignment: Alignment.topLeft,
                  height: 200,
                  child: TextField(
                    controller: textFieldEditer,
                    maxLines: 10,
                    // maxLength: 300,
                    autofocus: false,
                    decoration: InputDecoration(
                      hintText: "请输入交接内容",
                      hintMaxLines: 20,
                      fillColor: Colours.bg_color,
                      filled: true,
                      border: InputBorder.none,
                    ),
                  ),
                ),
                // Gaps.vGap15,
                Container(
                  padding: EdgeInsets.only(right: 15),
                  alignment: Alignment.centerRight,
                  child: TextButton(
                    style: ButtonStyle(
                        backgroundColor:
                            WidgetStateProperty.all(Colours.text_gray)),
                    onPressed: () {
                      if (TextUtil.isEmpty(textFieldEditer.text)) {
                        Toast.show('请输入交接内容');
                        return;
                      }
                      _addContentData(reportId ?? 0, info);
                      Navigator.pop(context);
                    },
                    child: Text(
                      '发布',
                      style: TextStyle(color: Colours.text_dark),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  _addContentData(int reportId, HandoverElderInfoEntity info) {
    var map = {
      'reportId': reportId,
      'customerElderId': info.customerElderId,
      'content': textFieldEditer.text,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.shiftingDutyCreate}', data: map)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          _fectData();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///添加报告总结
  _bottomAddReportArchiveSheetAlert(int reportId) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets,
          duration: Duration(milliseconds: 400),
          child: StatefulBuilder(
            builder: (context, setDialogState) {
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Gaps.vGap16,
                  Text(
                    '交接班总结11',
                    style: TextStyle(fontSize: 20, color: Colours.text_dark),
                  ),
                  Gaps.vGap15,
                  Container(
                    padding: EdgeInsets.all(20),
                    color: Colors.white,
                    alignment: Alignment.topLeft,
                    height: 200,
                    child: TextField(
                      controller: archiveTextFieldEditer,
                      maxLines: 10,
                      // maxLength: 300,
                      autofocus: true,
                      decoration: InputDecoration(
                        hintText: "请输入交接班总结",
                        hintMaxLines: 10,
                        fillColor: Colours.bg_color,
                        filled: true,
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(right: 15, left: 15, bottom: 15),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        ChoiceChip(
                          label: Text('归档'),
                          backgroundColor: Colours.bg_gray,
                          selectedColor: Colours.app_main,
                          selected: _archive,
                          onSelected: (value) {
                            setDialogState(() {
                              _archive = value;
                            });
                          },
                        ),
                        FlatsButton(
                          color: Colours.text_gray,
                          onPressed: () {
                            if (TextUtil.isEmpty(archiveTextFieldEditer.text)) {
                              Toast.show('请输入总结内容');
                              return;
                            }
                            _addReportArchiveData(reportId);
                            Navigator.pop(context);
                          },
                          child: Text(
                            '发布',
                            style: TextStyle(color: Colours.text_dark),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              );
            },
          ),
        );
      },
    );
  }

  _addReportArchiveData(int reportId) {
    var map = {
      'id': reportId,
      'archive': _archive ? 1 : 0,
      'summary': archiveTextFieldEditer.text,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.shiftingDutyArchive}', data: map)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          _fectData();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
